import grails.util.GrailsUtil
import com.goal98.team.domain.Person
import com.goal98.team.domain.Authority
import com.goal98.team.domain.Team
import com.goal98.team.domain.Position
import com.goal98.team.domain.Venue
import com.goal98.team.domain.Activity
import com.goal98.team.Constants
import com.goal98.grails.plugin.account.domain.Credit
import com.goal98.grails.plugin.account.domain.Account

class BootStrap {

    def fixtureLoader
    def authenticateService
    def eventConsumerService
    def searchableService
    def accountService
    def myteamService
    def personService
    def playerService
    def activityService

    def init = {servletContext ->

        eventConsumerService.init()

        final String env = GrailsUtil.environment
        final def adminPassword = authenticateService.encodePassword('lc541116')
        final def adminPassword2 = authenticateService.encodePassword('111111')

        if (env == 'development'
//                || env == 'test'
        ) {


            if (System.getProperty('hugeData')) {

                fixtureLoader.load {

                    admin(Person) {
                        userRealName = '系统管理员'
                        passwd = adminPassword
                        username = 'admin@gmail.com'
                        enabled = true
                    }

                    roleAdmin(Authority) {
                        authority = Constants.ROLE_ADMIN
                        description = '系统管理员'
                        people = [admin]
                    }

                    roleTeamAdmin(Authority) {
                        authority = Constants.ROLE_TEAM_ADMIN
                        description = '球队管理员'

                    }

                    basicUser(Authority) {
                        authority = Constants.ROLE_BASIC_MEMBER
                        description = '普通用户'
                    }

                    positionFW(Position) {
                        name = "前锋"
                        x = 50
                        y = 80

                    }

                    positionMF(Position) {
                        name = "中场"
                        x = 50
                        y = 50

                    }

                    positionCB(Position) {
                        name = "后卫"
                        x = 50
                        y = 30

                    }

                    positionGK(Position) {
                        name = "门将"
                        x = 50
                        y = 10

                    }


                }

                def teamNo = 1000
                def playerPerTeam = 20
                def activityPerTeam = 100
                def venueNo = 500
                def creditPerPlayer = 10


                def batchSize = 100
                def batch = []

                Venue.withSession {session ->
                    venueNo.times {i ->
                        def venue = new Venue(
                                name: "Venue $i",
                                costAmount: 500,
                                timeCanPlay: 4,
                                lat: '31.19309',
                                lng: '121.598997',
                        )

                        batch << venue

                        checkBatch(batch, batchSize, i, venueNo, session)

                    }
                }

                def venue1 = Venue.get(1)
                def position = Position.get(1)
                def playerAuth = Authority.findByAuthority(Constants.ROLE_BASIC_MEMBER)
                def teamAdminAuth = Authority.findByAuthority(Constants.ROLE_TEAM_ADMIN)

                batchSize = 100

                Team.withSession {session ->
                    teamNo.times {i ->
                        def team = new Team(name: "Team $i")

                        Account account = new Account(reference: team.name, balance: 0)
                        team.account = account

                        activityPerTeam.times {j ->
                            def activity = new Activity(
                                    activityTime: new Date(),
                                    venue: venue1,
                                    description: '',
                                    actualPersonCount: 30
                            )
                            team.addToActivities(activity)

                        }

                        playerPerTeam.times {j ->
                            def player = new Person(
                                    username: "player${i}_${j}@goal98.com",
                                    userRealName: "Player ${i}-${j}",
                                    enabled: true,
                                    passwd: adminPassword2,
                                    position: position)

                            player.account = new Account(reference: player.username, balance: 0)

                            creditPerPlayer.times {
                                credit(player.account, 30, 'weekly fee')
                            }

                            if (j == 0) {
                                player.addToAuthorities(teamAdminAuth)
                            } else {
                                player.addToAuthorities(playerAuth)
                            }

                            team.addToMembers(player)
                            team.activities.each {activity ->
                                player.addToActivityAttend(activity)
                            }
                        }

                        batch << team

                        if (batch.size() > batchSize || i == teamNo - 1) {
                            Team.withTransaction {
                                batch.each {_team->
                                    _team.save()
                                    _team.account.save()
                                    _team.members.each{_player->
                                        _player.account.save()    
                                    }

                                }
                            }
                            session.clear()
                            batch.clear()
                        }
                    }
                }

            } else {
                fixtureLoader.load('initDataDev')

                fixtureLoader.load {

                    venueZhongYiDa(Venue) {
                        name = "中医药大学"
                        costAmount = 500
                        timeCanPlay = 4
                        lat = '31.19309'
                        lng = '121.598997'

                    }

                    venueFuDanZhangJiang(Venue) {
                        name = "复旦张江校区"
                        costAmount = 350
                        timeCanPlay = 2
                        lat = '31.194668'
                        lng = '121.616284'

                    }

                    positionFW(Position) {
                        name = "前锋"
                        x = 50
                        y = 80

                    }

                    positionMF(Position) {
                        name = "中场"
                        x = 50
                        y = 50

                    }

                    positionCB(Position) {
                        name = "后卫"
                        x = 50
                        y = 30

                    }

                    positionGK(Position) {
                        name = "门将"
                        x = 50
                        y = 10

                    }

                    teamA(Team) {
                        name = '山寨巴萨队'
                    }

                    teamB(Team) {
                        name = '山寨皇马队'
                    }

                    teamPuDong(Team) {
                        name = '浦东队'
                    }

                    //Activities
                    sampleActivity(Activity) {
                        activityTime = new Date()
                        team = teamPuDong
                        venue = venueZhongYiDa
                        description = '跟蚂蚁联队比赛'
                    }

                    //Users start
                    admin(Person) {
                        userRealName = '系统管理员'
                        passwd = adminPassword
                        username = 'admin@gmail.com'
                        enabled = true
                        team = teamA
                    }

                    teamAdmin(Person) {
                        userRealName = '队长超'
                        passwd = adminPassword
                        username = 'tadmin@gmail.com'
                        enabled = true
                        team = teamA
                    }

                    player(Person) {
                        userRealName = '刘超'
                        passwd = adminPassword
                        username = 'player@gmail.com'
                        enabled = true
                        team = teamA
                    }

                    player2(Person) {
                        userRealName = 'C 罗'
                        passwd = adminPassword
                        username = 'c.r@gmail.com'
                        enabled = true
                        team = teamB
                    }

                    playerNoTeam(Person) {
                        userRealName = '无球队球员'
                        passwd = adminPassword
                        username = 'noteam@gmail.com'
                        enabled = true
                    }

                    playerNotEnabled(Person) {
                        userRealName = '未激活球员'
                        username = 'notenable@gmail.com'
                        enabled = false
                    }

                    teamAdminPuDong(Person) {
                        userRealName = '树熊'
                        passwd = adminPassword2
                        username = '44534186@qq.com'
                        enabled = true
                        team = teamPuDong
                        position = positionGK
                    }

                    playerLiuChao(Person) {
                        userRealName = '刘超'
                        passwd = adminPassword
                        username = 'liuchao36@gmail.com'
                        enabled = true
                        team = teamPuDong
                        position = positionCB
                        receiveEmail = true
                        activityAttend = [sampleActivity]
                    }

                    playerMaoJun(Person) {
                        userRealName = '毛军'
                        passwd = adminPassword
                        username = '783620191@qq.com'
                        enabled = true
                        team = teamPuDong
                        position = positionFW
                    }

                    playerZongPing(Person) {
                        userRealName = '郁宗平'
                        passwd = adminPassword
                        username = '284466472@qq.com'
                        enabled = true
                        team = teamPuDong
                        position = positionMF
                    }

                    playerDaWeiWang(Person) {
                        userRealName = '大卫王'
                        passwd = adminPassword
                        username = 'davywang_1978@qq.com'
                        enabled = true
                        team = teamPuDong
                        position = positionCB
                    }

                    //Users end


                    roleAdmin(Authority) {
                        authority = Constants.ROLE_ADMIN
                        description = '系统管理员'
                        people = [admin]

                    }

                    roleTeamAdmin(Authority) {
                        authority = Constants.ROLE_TEAM_ADMIN
                        description = '球队管理员'
                        people = [teamAdmin, teamAdminPuDong]

                    }

                    basicUser(Authority) {
                        authority = Constants.ROLE_BASIC_MEMBER
                        description = '普通用户'
                        people = [player, player2, playerNoTeam, playerNotEnabled, playerLiuChao, playerDaWeiWang, playerZongPing, playerMaoJun]
                    }


                }

                searchableService.index();
            }



        }


    }

    def checkBatch(batch, int batchSize, i, int venueNo, session) {
        if (batch.size() > batchSize || i == venueNo - 1) {
            Venue.withTransaction {
                batch.each {
                    it.save()
                }
            }
            session.clear()
            batch.clear()
        }
    }

    def credit(Account account, BigDecimal amount, String description) {
        account.credit(amount)
        Credit credit = new Credit()
        credit.description = description
        credit.amount = amount
        account.addToTransactions(credit)
    }

    def destroy = {
    }
} 